import os

from PIL import Image, ImageDraw, ImageFont


def pic2char0(char_frames_dir, pro_frames_dir, picsize=1, clarity=0.1, fontsize=10, skip=1, model="L"):
    """
        将提取出的动图帧转换为字符图
    :param char_frames_dir: 字符每帧图片文件夹
    :param pro_frames_dir: 原型每帧图片文件夹
    :param picsize: 输出图像为原图倍数
    :param clarity: 可理解为清晰度，先把原图resize缩放clarity倍，再提取像素写成字符，故越小越模糊
    :param fontsize: 字符大小
    :param skip: 原视频FPS过大，转换效率过低时选用，即降低FPS来获取速度。当原为FPS=30，输出FPS=10时，即skip=3，可保持与视频同进度
    :param model: 灰度 L，彩图 RGB
    :return: None
    """
    if not os.path.exists(char_frames_dir):
        os.makedirs(char_frames_dir)

    number = len([i for i in os.listdir(pro_frames_dir) if i.endswith(".jpg")])
    jpglist = [f"{pro_frames_dir}/{i + 1}.jpg" for i in range(0, number, skip)]  # 直接读取可能非顺序帧

    for i, jpg in enumerate(jpglist):
        img = Image.open(jpg)
        width, height = img.size

        width1 = int(width * clarity)
        height1 = int(height * clarity)
        img_without_color = img.convert('L').resize((width1, height1))

        width_new = int(width * picsize)
        height_new = int(height * picsize)
        if model == "RGB":
            img_with_color = img.resize((width1, height1))
            img_new = Image.new('RGB', (width_new, height_new), "white")
        else:
            img_new = Image.new('L', (width_new, height_new), "white")

        draw_object = ImageDraw.Draw(img_new)
        # 指定长宽等尺寸地字体
        font = ImageFont.truetype('consola.ttf', fontsize, encoding='unic')

        charlist = "@W#$OEXC[(/?=^~_.` "
        for row in range(height1):
            for col in range(width1):
                char = img_without_color.getpixel((col, row))
                if model == "RGB":
                    color = img_with_color.getpixel((col, row))
                    draw_object.text((int(col * picsize / clarity), int(row * picsize / clarity)),
                                     charlist[int(char * 18 / 255)],
                                     font=font, fill=color)
                else:
                    draw_object.text((int(col * picsize / clarity), int(row * picsize / clarity)),
                                     charlist[int(char * 18 / 255)],
                                     font=font,fill=0)

        img_new.save(char_frames_dir + f"/{os.path.basename(jpg)}")

        print(f"进度{(i + 1)}/{len(jpglist)}， 转换 {jpg} 为字符图片 完成！")

    print("图片转为字符图片完成！")


if __name__ == "__main__":
    pic2char0("fumo/fumo_char_frames00","fumo/fumo_pro_frames", clarity=0.2, skip=1)